package com.cn.nio.multinio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
/**
 * 负责 监听 连接
 */
public class AcceptorThread extends Thread {


    Selector bossSelector;    //负责监听连接的seletor

    AtomicInteger id = new AtomicInteger();

    int thread;

    public AcceptorThread(ServerSocketChannel serverChannel, int thread) throws IOException {
        this.thread = thread;
        NioMultiThread3.queue = new LinkedBlockingQueue[thread];
        for (int i = 0; i < thread; i++) {
            NioMultiThread3.queue[i] = new LinkedBlockingQueue<>();
        }

        //epoll_create
        bossSelector = Selector.open();

        //epoll_ctl 注册
        serverChannel.register(bossSelector, SelectionKey.OP_ACCEPT);
    }

    @Override
    public void run() {
        while (true) {
            try {
                this.bossSelector.select();
                String name = Thread.currentThread().getName();

                Set<SelectionKey> selectionKeys = this.bossSelector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    //事件监听过了 就移除
                    iterator.remove();
                    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
                    if (selectionKey.isAcceptable()) {
                         log.info(name + " 获取了连接事件 {} ", selectionKey);
                        int i = id.incrementAndGet() % thread;
//                        try {
//
//                            //1 建立好链接放到queue中交给 工作线程使用
//                            SocketChannel socketChannel = serverSocketChannel.accept();
//                            if (socketChannel != null) {
//                                socketChannel.configureBlocking(false);
//                                log.info("建立连接 -> {} ", socketChannel);
////                                socketChannel.register(worksSelector, SelectionKey.OP_READ); //从队列 获取 建立的连接，同时注册
//                                NioMultiThread3.queue[i].put(socketChannel);
//                            }
//                            //2 交给工作现成 自己去建立链接
////                            NioMultiThread3.queue[i].put(serverSocketChannel);
//
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }

                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
